package com.feeyo.groundservice.http.exception

import com.feeyo.groundservice.http.constant.BAD_NETWORK
import com.feeyo.groundservice.http.constant.BUSINESS_CODE_EXCEPTION
import com.feeyo.groundservice.http.constant.CONNECT_ERROR
import com.feeyo.groundservice.http.constant.CONNECT_TIMEOUT
import com.feeyo.groundservice.http.constant.PARSE_ERROR
import com.feeyo.groundservice.http.constant.SERVER_RESPONSE_ERROR
import com.feeyo.groundservice.http.constant.UNKNOWN_ERROR
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 *作者：QLH on 2023-09-15
 *描述：异常的原因
 */
internal enum class ExceptionReason {
    /**
     * 解析数据失败
     */
    PARSE_ERROR,

    /**
     * 网络问题
     */
    BAD_NETWORK,

    /**
     * 连接错误
     */
    CONNECT_ERROR,

    /**
     * 连接超时
     */
    CONNECT_TIMEOUT,

    /**
     * 未知错误
     */
    UNKNOWN_ERROR,

    /**
     * 服务器响应异常
     * **/
    SERVER_RESPONSE_ERROR,

    /**业务异常**/
    BUSINESS_EXCEPTION
}

internal object ExceptShow {
    fun onShowException(reason: ExceptionReason, msg: String? = null) {
        when (reason) {
            ExceptionReason.CONNECT_ERROR -> toast(CONNECT_ERROR)

            ExceptionReason.CONNECT_TIMEOUT -> toast(CONNECT_TIMEOUT)

            ExceptionReason.BAD_NETWORK -> toast(BAD_NETWORK)

            ExceptionReason.PARSE_ERROR -> toast(PARSE_ERROR)

            ExceptionReason.UNKNOWN_ERROR -> toast(UNKNOWN_ERROR)

            ExceptionReason.SERVER_RESPONSE_ERROR -> toast(SERVER_RESPONSE_ERROR)

            ExceptionReason.BUSINESS_EXCEPTION -> toast(msg ?: BUSINESS_CODE_EXCEPTION)
        }
    }

    //toast
    @OptIn(DelicateCoroutinesApi::class)
    private fun toast(msg: String?) {
        GlobalScope.launch(Dispatchers.Main) {
            msg?.run {
                //Toast.makeText(Utils.getApp(), this, Toast.LENGTH_SHORT).show()
                (this)
            }
        }
    }
}

//[-200,-100] 业务方不要占用了，作为预留全局公共错误码
internal object ExceptionErrorCode {
    const val PARSE_ERROR_CODE = -200
    const val BAD_NETWORK_CODE = -199
    const val CONNECT_ERROR_CODE = -198
    const val CONNECT_TIMEOUT_CODE = -197
    const val SERVER_RESPONSE_CODE = -196
    const val UNKNOWN_ERROR_CODE = -195
    const val DATA_NULL_CODE = -194
    const val UNKNOWN_CODE = -999
}